from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from typing import List, Optional
from sqlalchemy.orm import Session
from database import get_db
from crud import get_routes, get_route, create_route, update_route, delete_route, get_route_details
from models import Route as RouteModel, Landmark as LandmarkModel
from auth import get_current_active_user

router = APIRouter(prefix="/api/routes", tags=["routes"])

# 数据模型
class Route(BaseModel):
    id: Optional[int] = None
    name: str
    landmarks: List[int] = []

class RouteDetail(BaseModel):
    id: Optional[int] = None
    name: str
    landmarks: List[dict] = []
    creator_id: Optional[int] = None
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

# API路由 - 路径相关
@router.get("/", response_model=List[Route])
async def get_routes_route(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取所有路径"""
    # 此接口为公开访问，不需要认证
    routes = get_routes(db, skip=skip, limit=limit)
    result = []
    for route in routes:
        landmark_ids = [landmark.id for landmark in route.landmarks]
        result.append(Route(
            id=route.id,
            name=route.name,
            landmarks=landmark_ids
        ))
    return result

@router.get("/{id}", response_model=Route)
async def get_route_route(request: Request, id: int, db: Session = Depends(get_db)):
    """获取指定路径"""
    # 此接口为公开访问，不需要认证
    route = get_route(db, route_id=id)
    if not route:
        raise HTTPException(status_code=404, detail="路径未找到")

    landmark_ids = [landmark.id for landmark in route.landmarks]
    return Route(
        id=route.id,
        name=route.name,
        landmarks=landmark_ids
    )

@router.get("/{id}/details", response_model=RouteDetail)
async def get_route_details_route(request: Request, id: int, db: Session = Depends(get_db)):
    """获取路径详细信息（包含地标详情）"""
    # 此接口为公开访问，不需要认证
    route_details = get_route_details(db, route_id=id)
    if not route_details:
        raise HTTPException(status_code=404, detail="路径未找到")

    landmarks_data = []
    for landmark in route_details["landmarks"]:
        landmarks_data.append({
            "id": landmark.id,
            "name": landmark.name,
            "lat": landmark.lat,
            "lng": landmark.lng,
            "summary": landmark.summary,
            "details": landmark.details,
            "media": landmark.media
        })

    return RouteDetail(
        id=route_details["id"],
        name=route_details["name"],
        landmarks=landmarks_data,
        creator_id=route_details["creator_id"],
        created_at=route_details["created_at"].isoformat() if route_details["created_at"] else None,
        updated_at=route_details["updated_at"].isoformat() if route_details["updated_at"] else None
    )

@router.post("/", response_model=Route)
async def create_route_route(request: Request, route: Route, db: Session = Depends(get_db)):
    """创建新路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    db_route = create_route(
        db=db,
        name=route.name,
        creator_id=current_user.id,
        landmark_ids=route.landmarks
    )

    landmark_ids = [landmark.id for landmark in db_route.landmarks]
    return Route(
        id=db_route.id,
        name=db_route.name,
        landmarks=landmark_ids
    )

@router.put("/{id}", response_model=Route)
async def update_route_route(request: Request, id: int, route: Route, db: Session = Depends(get_db)):
    """更新路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    db_route = update_route(
        db=db,
        route_id=id,
        name=route.name,
        landmark_ids=route.landmarks
    )

    if not db_route:
        raise HTTPException(status_code=404, detail="路径未找到")

    landmark_ids = [landmark.id for landmark in db_route.landmarks]
    return Route(
        id=db_route.id,
        name=db_route.name,
        landmarks=landmark_ids
    )

@router.delete("/{id}")
async def delete_route_route(request: Request, id: int, db: Session = Depends(get_db)):
    """删除路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    success = delete_route(db, route_id=id)
    if not success:
        raise HTTPException(status_code=404, detail="路径未找到")

    return {"message": "路径已删除"}
